/**
 * Copyright (c) 2016-2019 九点科技 All rights reserved.
 *
 * http://www.9dyun.cn
 *
 * 版权所有，侵权必究！
 */
package com.dian.modules.sale.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dian.common.utils.*;
import com.dian.common.validator.ValidatorUtils;
import com.dian.common.validator.group.AddGroup;
import com.dian.common.validator.group.UpdateGroup;
import com.dian.modules.enums.sale.OrderHead_OrderStateEnum;
import com.dian.modules.sale.service.ProbHeadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dian.common.exception.RRException;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections.CollectionUtils;
import com.dian.common.server.CommonService;
import com.dian.modules.sale.dao.OrderHeadDao;
import com.dian.modules.sale.entity.OrderHeadEntity;
import com.dian.modules.sale.service.OrderHeadService;
import com.dian.modules.sale.service.OrderLineService;
import com.dian.modules.sale.entity.OrderLineEntity;
import com.dian.modules.sale.service.OrderLineService;
import com.dian.modules.sale.vo.OrderHeadExportVO;
import com.dian.modules.sale.vo.OrderLineExportVO;

/**
 * 销售订单表服务实现类
 *
 * @author xiaolai
 * @email xiaolai@9dyun.cn
 * @date 2019-06-18 16:59:32
 */
@Service("orderHeadService")
public class OrderHeadServiceImpl extends ServiceImpl<OrderHeadDao, OrderHeadEntity> implements OrderHeadService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public CommonService commonService;

    @Autowired
    public OrderLineService orderLineService;


    @Autowired
    public ProbHeadService probHeadService;

    /**
     * 销售订单表分页
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderHeadEntity> page = this.page(new Query<OrderHeadEntity>().getPage(params),getQueryWrapper(params) );
        return new PageUtils(page);
    }

    /**
    *  销售订单表新增
    * @param orderHeadEntity
    * @return
    */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveInfo(OrderHeadEntity orderHeadEntity) {

        //检查是否已经生成过销售计单
        probHeadService.checkCreateSaleOrder(orderHeadEntity.getProbId());


        //设置编码，基础默然初始化数据设置
        //orderHeadEntity.setOrderDate(new Date());
        orderHeadEntity.setOrderNo(commonService.getCode(OrderHeadEntity.class));
        orderHeadEntity.setOrderMonth(new Date().toText2());

        this.paramsCheck(orderHeadEntity,AddGroup.class);


        //保存主表
        this.save(orderHeadEntity);

        //保存从表
        if (CollectionUtils.isNotEmpty(orderHeadEntity.getOrderLineEntityList())) {
            List<OrderLineEntity> detailList = orderHeadEntity.getOrderLineEntityList();
            for (OrderLineEntity detail : detailList) {
                detail.setOrderId(orderHeadEntity.getId());
            }
            orderLineService.saveBatch(orderHeadEntity.getOrderLineEntityList());
        }
        return true;
    }

    /**
     *销售订单表更新
     * @param orderHeadEntity
     * @return
     */
    @Override
    public boolean updateInfo(OrderHeadEntity orderHeadEntity) {

        //修改状态校验
        this.updateCheck(orderHeadEntity.getId());

        //主表数据完整性校验
        this.paramsCheck(orderHeadEntity, UpdateGroup.class);

        //更新主表
        this.updateById(orderHeadEntity);

        //更新从表
        orderLineService.updateInfo(orderHeadEntity);


        return true;
    }

    /**
     *销售订单表删除
     * @param id
     * @return
     */
    @Override
    public boolean deleteInfo(Long id) {

        //删除状态校验
        this.deleteCheck(id);

        //更新从表
        orderLineService.deleteInfo(id);

        //更新主表
        this.remove(new QueryWrapper<OrderHeadEntity>().eq("id",id));

        return true;
    }

    /**
     * 销售订单表详情
     * @param id
     * @return
     */
    @Override
    public OrderHeadEntity getInfo(Long id) {
        OrderHeadEntity orderHeadEntity =getById(id);
        List<OrderLineEntity> lineList=orderLineService.queryLineList(id);
        orderHeadEntity.setOrderLineEntityList(lineList);
        return orderHeadEntity;
    }

    /**
     * 销售订单表审核
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean checkInfo(Long id) {
        OrderHeadEntity orderHeadEntity =this.getById(id);
        checkCheck(orderHeadEntity);
        orderHeadEntity.setOrderState(OrderHead_OrderStateEnum.AUDITED.getValue());
        orderHeadEntity.setCheckDate(new Date());
        orderHeadEntity.setCheckUserId(commonService.getUserId());
        orderHeadEntity.setCheckUserName(commonService.getUserName());
        return this.updateById(orderHeadEntity);
    }

    /**
     * 预订单分页导出
     * @param params
     * @return
     */
    @Override
    public List<OrderHeadExportVO> exportList(Map<String, Object> params) {
        List<OrderHeadEntity> list;
        Integer exprotType= PUtil.getParaToInt(params.get("exprotType"),0);
        if(exprotType==0){
            //导出当前页
            list= this.page(new Query<OrderHeadEntity>().getPage(params),getQueryWrapper(params)).getRecords();
        }else{
            //导出全部
            list= this.list(getQueryWrapper(params));
        }
        List<OrderHeadExportVO> resultList = BeanConverter.convertList(list, OrderHeadExportVO.class);
        // 封装明细
        if(CollectionUtils.isNotEmpty(resultList)){
            for(OrderHeadExportVO orderHeadEntity : resultList){
                List<OrderLineEntity>  orderLineEntityList = orderLineService.queryLineList(orderHeadEntity.getId());
                orderHeadEntity.setOrderLineExportVOList(BeanConverter.convertList( orderLineEntityList, OrderLineExportVO.class));
            }
        }
        return resultList;
    }

    /**
     * 查询预订单使用库存
     * @param goodsId
     * @return
     */
    @Override
    public BigDecimal useSaleQty(Long  goodsId){

        return getBaseMapper().useSaleQty(goodsId);
    }

    /***********************************************************************************************/
    /****************************************** 私有方法 ********************************************/
    /***********************************************************************************************/

    /**
     * 修改状态校验
     *
     * @param
     */
    private void updateCheck(Long id) {
        OrderHeadEntity orderHeadEntity =this.getById(id);
        if(orderHeadEntity.getOrderState().equals(OrderHead_OrderStateEnum.AUDITED.getValue())){
             throw new RRException(String.format("[%s] 当前订单已审核状态,禁止修改",orderHeadEntity.getOrderNo()));
        }
    }
    /**
     * 审核状态校验
     *
     * @param
     */
    private void checkCheck(OrderHeadEntity orderHeadEntity) {

        if(orderHeadEntity.getOrderState().equals(OrderHead_OrderStateEnum.AUDITED.getValue())){
            throw new RRException(String.format("[%s] 当前订单已审核状态,禁止审核",orderHeadEntity.getOrderNo()));
       }
    }

    /**
     * 删除状态校验
     *
     * @param
     */
    private void deleteCheck(Long id) {
        OrderHeadEntity orderHeadEntity =this.getById(id);
        if(!orderHeadEntity.getOrderState().equals(OrderHead_OrderStateEnum.WAITCHECK.getValue())){
           throw new RRException(String.format("[%s] 当前订单已审核状态,禁止删除",orderHeadEntity.getOrderNo()));
        }
    }

    /**
     * 新增和修改参数校验
     *
     * @param record
     */
    private void paramsCheck(OrderHeadEntity record, Class<?> cls) {
        //设置明细的主表ID
        ListUtils.setPropertyValue(record.getOrderLineEntityList(),"orderId",record.getId());

        ValidatorUtils.validateEntity(record, cls);

        if (CollectionUtils.isEmpty(record.getOrderLineEntityList())) {
            throw new RRException("销售订单表明细数据不能为空");
        }
        for (OrderLineEntity orderLineEntity : record.getOrderLineEntityList()) {
            int index = record.getOrderLineEntityList().indexOf(orderLineEntity) + 1;
            try {
                ValidatorUtils.validateEntity(orderLineEntity, Arrays.asList("orderId"), cls);
            }catch (RRException e){
                throw new RRException(String.format("第%s行 销售订单明细校验失败<br/>"+e.getMsg(), index));
            }
        }
    }

    /**
     * 获取查询条件
     *
     * @param
     */
    private QueryWrapper<OrderHeadEntity> getQueryWrapper(Map<String, Object> params) {
        QueryWrapper<OrderHeadEntity> queryWrapper=new QueryWrapper<>();
        if(!StrUtil.isBlankIfStr(params.get("orderDate"))){
            String orderDate=String.valueOf(params.get("orderDate"));
            String[] orderDateRange=orderDate.split("至");
            if(orderDateRange.length==2){
                queryWrapper.gt("order_date",DateUtils.getBeginTimeOfDate(orderDateRange[0]));
                queryWrapper.lt("order_date",DateUtils.getBeginTimeOfDate(orderDateRange[1]));
            }else{
                queryWrapper.gt("order_date",DateUtils.getBeginTimeOfDate(orderDate));
            }
        }
        if(!StrUtil.isBlankIfStr(params.get("probId"))){
            queryWrapper.eq("prob_id",params.get("probId"));
        }
        if(!StrUtil.isBlankIfStr(params.get("orderNo"))){
            queryWrapper.likeLeft("order_no",params.get("orderNo"));
        }
        /*if(!StrUtil.isBlankIfStr(params.get("customerCode"))){
            queryWrapper.likeLeft("customer_code",params.get("customerCode"));
        }*/
        if(!StrUtil.isBlankIfStr(params.get("orderState"))){
            queryWrapper.likeLeft("order_state",params.get("orderState"));
        }
        queryWrapper.orderByAsc("id");
        return queryWrapper;
    }
}
